﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenCvSharp;
using System.Runtime.InteropServices;

namespace LicenseAutoDetection
{
    class GrayHistogram : IDisposable
    {
        uint[] Hist = new uint[256];

        public bool Division(IplImage _src, int _ColorBound = 240)
        {
            uint ColorData = 0;

            Extract(_src);

            uint LowimageData = (uint)((_src.Height * _src.Width) * 0.60);
            uint HighimageData = (uint)((_src.Height * _src.Width) * 0.995);
            for (int i = _ColorBound; i < 256; i++) ColorData += Hist[i];

            return (LowimageData < ColorData && ColorData < HighimageData) ? true : false;
        }

        private void Extract(IplImage _src)
        {
            IntPtr ptr;
            int idxHei = 0;

            ptr = _src.ImageData;

            for (int Hei = 0; Hei < _src.Height; Hei++)
            {
                idxHei = _src.WidthStep * Hei;
                for (int Wid = 0; Wid < _src.Width; Wid++)
                {
                    Hist[Marshal.ReadByte(ptr, idxHei + Wid)]++;
                }
            }
        }

        #region IDisposable 구현
        private bool disposed = false;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (Hist != null) { Array.Clear(Hist, 0, Hist.Length); Hist = null; }
                }

                disposed = true;
            }
        }

        ~GrayHistogram()
        {
            Dispose(false);
        }
        #endregion
    }
}
